#include "kdcchaptereditor.h"

#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QGridLayout>
#include <QRadioButton>
#include <QStringList>
#include <QListWidgetItem>
#include <QPixmap>
#include <QTime>

#include <KIcon>
#include <KLocale>
#include <KMessageBox>
#include <KAction>
#include <KPushButton>
#include <KVBox>
#include <KHBox>

#include <kdclib.h>
#include <kdcmovie.h>
#include <interfaces/kdcmediaplayerinterface.h>
extern KDCMediaPlayerInterface *gKDCMediaPlayer;
#include <interfaces/kdcjobsinterface.h>
extern KDCJobsInterface *gKDCJobsInterface;
#include <interfaces/kdcstatusbarinterface.h>
extern KDCStatusBarInterface *gKDCStatusBar;

KDCChapterEditor::KDCChapterEditor( QWidget *aParent ) : QWidget( aParent ), pChapter( NULL )
{
	pChapterMode = new KButtonGroup( this );
	pChapterMode->setCheckable( true );
	pChapterMode->setTitle( i18n("Chapters") );
	
	QVBoxLayout *vLayout = new QVBoxLayout( pChapterMode );
	QGridLayout *gLayout = new QGridLayout;
	QRadioButton *numRadio = new QRadioButton( i18n("Set number of chapers"), this ); // id = 0
	pNumChapter = new KIntNumInput( this );
	pNumChapter->setRange( 2, 30 );
	connect( numRadio, SIGNAL( toggled( bool ) ), pNumChapter, SLOT( setEnabled( bool ) ) );
	KPushButton *btn = new KPushButton( KIcon("view-refresh"), i18n("Apply"), this );
	connect( numRadio, SIGNAL( toggled( bool ) ), btn, SLOT( setEnabled( bool ) ) );
	connect( btn, SIGNAL( clicked() ), this, SLOT( createFromSize() ) );
	gLayout->addWidget( numRadio, 0, 0 );
	gLayout->addWidget( pNumChapter, 0, 1 );
	gLayout->addWidget( btn, 0, 2 );

	QRadioButton *timeRadio = new QRadioButton( i18n("Set new chaper every ( sec )"), this ); // id = 1
	pTimeChapter = new KIntNumInput( this );
	pTimeChapter->setEnabled( false );
	pTimeChapter->setRange( 1, 1000 );
	connect( timeRadio, SIGNAL( toggled( bool ) ), pTimeChapter, SLOT( setEnabled( bool ) ) );
	btn = new KPushButton( KIcon("view-refresh"), i18n("Apply"), this );
	connect( timeRadio, SIGNAL( toggled( bool ) ), btn, SLOT( setEnabled( bool ) ) );
	connect( btn, SIGNAL( clicked() ), this, SLOT( createFromLength() ) );
	gLayout->addWidget( timeRadio, 1, 0 );
	gLayout->addWidget( pTimeChapter, 1, 1 );
	gLayout->addWidget( btn, 1, 2 );

	QRadioButton *mediaRadio = new QRadioButton( i18n("Get chapters from Media Player"), this ); // id = 2
	btn = new KPushButton( KIcon("list-add"), i18n("Get"), this );
	connect( btn, SIGNAL( clicked() ), this, SLOT( getChapterFromPlayer() ) );
	connect( mediaRadio, SIGNAL( toggled( bool ) ), btn, SLOT( setEnabled( bool ) ) );
	btn->setEnabled( false );
	gLayout->addWidget( mediaRadio, 2, 0, 1, 1 );
	gLayout->addWidget( btn, 2, 2 );
	vLayout->addLayout( gLayout );
	vLayout->addStretch();

	KHBox *hBox = new KHBox( this );
	btn = new KPushButton( KIcon("process-stop"), i18n("Abort"), hBox );
	connect( btn, SIGNAL( clicked() ), this, SLOT( abort() ) );
	btn = new KPushButton( KIcon("edit-clear-list"), i18n("Delete All"), hBox );
	connect( btn, SIGNAL( clicked() ), this, SLOT( deleteALL() ) );
	connect( pChapterMode, SIGNAL( toggled( bool ) ), hBox, SLOT( setEnabled( bool ) ) );
	vLayout->addWidget( hBox );
	
	QHBoxLayout *mainLayout = new QHBoxLayout( this );
	mainLayout->addWidget( pChapterMode );

	KVBox *vBox = new KVBox( this );
	pView = new KListWidget( vBox );
	pView->setViewMode( QListView::IconMode );
	pView->setIconSize( QSize( 112, 63 ) );
	pView->setSpacing( 12 );
	pView->setMovement( QListView::Static );
	pView->setResizeMode( QListView::Adjust );
	pView->setContextMenuPolicy( Qt::ActionsContextMenu );
	pProgress = new QProgressBar( vBox );
	pProgress->setMaximumHeight( 20 );
	connect( pChapterMode, SIGNAL( toggled( bool ) ), vBox, SLOT( setEnabled( bool ) ) );
	mainLayout->addWidget( vBox );
	
	pChapterMode->setSelected( 0 );

	KAction *del = new KAction( KIcon("edit-delete"), i18n("Delete selected"), pView );
	connect( del, SIGNAL( triggered() ), this, SLOT( removeChapters() ) );
}

KDCChapterEditor::~KDCChapterEditor()
{

}

void KDCChapterEditor::setChapter( KDCChapter *aChapter )
{
	pChapter = aChapter;
	pView->clear();
	setEnabled( pChapter );
	if ( pChapter )
		display();
}

void KDCChapterEditor::display()
{
	QPair<int,QPixmap> obj;
	pView->clear();
	for( int i=0; i<pChapter->count(); ++i )
	{
		obj = pChapter->chapter( i );
		addItem( i, obj.first, obj.second );
	}
}

void KDCChapterEditor::addItem( int aId, int aTime, const QPixmap &aPixmap )
{
	QListWidgetItem *item = new QListWidgetItem;
	item->setData( aId, Qt::EditRole );
	item->setText( QTime().addSecs( aTime ).toString("hh:mm:ss") );
	item->setIcon( QIcon( aPixmap ) );
	item->setFlags( Qt::ItemIsEnabled | Qt::ItemIsSelectable );
	item->setTextAlignment( Qt::AlignBottom | Qt::AlignHCenter );
	pView->addItem( item );
}

void KDCChapterEditor::createFromLength( int aDelta )
{
	KDCMovie *movie = static_cast<KDCMovie*>( pChapter->parent() );
	double length = movie->length();
	int size = qRound( length / aDelta );
	pProgress->setMaximum( size - 1 );
	int pos;
	for ( int i=0; i<size; ++i )
	{
		pos = aDelta*( i+1 );
		pChapterJobs.append( qMakePair( pos, gKDCJobsInterface->thumbnailJob( movieNameFromPos( movie, pos ), moviePos( movie, pos ) ) ) );
		connect( pChapterJobs.last().second, SIGNAL( result( KJob * ) ), this, SLOT( slotResult( KJob * ) ) );
	}
	pChapterJobs.first().second->start();
}

void KDCChapterEditor::createFromSize( int aSize )
{
	KDCMovie *movie = static_cast<KDCMovie*>( pChapter->parent() );
	double length = movie->length();
	int delta = qRound( length/( aSize + 1 ) );
	pProgress->setMaximum( aSize - 1 );
	int pos;
	for ( int i=0; i<aSize; ++i )
	{
		pos = delta*( i+1 );
		pChapterJobs.append( qMakePair( pos, gKDCJobsInterface->thumbnailJob( movieNameFromPos( movie, pos ), moviePos( movie, pos ) ) ) );
		connect( pChapterJobs.last().second, SIGNAL( result( KJob * ) ), this, SLOT( slotResult( KJob * ) ) );
	}
	pChapterJobs.first().second->start();
}

void KDCChapterEditor::slotResult( KJob *aJob )
{
	if ( aJob->error() )
	{
		KMessageBox::error( this, i18n("<b>There was an error during prosess:</b>%1").arg( aJob->errorString() ) );
		deleteALL();
	}
	else
	{
		pProgress->setValue( pProgress->value() + 1 );
		QPair<int,KDCFrameJobInterface*> obj = pChapterJobs.takeFirst();
		QPixmap frame = obj.second->resultFrame();
		addItem( pView->count(), obj.first, frame );
		pChapter->add( obj.first, frame );
		if ( !pChapterJobs.isEmpty() )
			pChapterJobs.first().second->start();
	}
}

void KDCChapterEditor::abort()
{
	deleteALL();
	deleteALL();
	gKDCStatusBar->showMessage( i18n("Proces was aborded."), KDC::Info );
}

void KDCChapterEditor::createFromSize()
{
	deleteALL();
	createFromSize( pNumChapter->value() );
}

void KDCChapterEditor::createFromLength()
{
	deleteALL();
	createFromLength( pTimeChapter->value() );
}

void KDCChapterEditor::getChapterFromPlayer()
{
	if ( !pChapter || !gKDCMediaPlayer || !gKDCJobsInterface )
		return;
	QString error;
	QPixmap pix = gKDCJobsInterface->getThumbnail( movieNameFromPos( 0, gKDCMediaPlayer->currentPos() ), gKDCMediaPlayer->currentPos(), error );
	if ( !error.isEmpty() )
		gKDCStatusBar->showMessage( i18n("Error during create thumbnail. ") + error, KDC::Error );
	else
	{
	  int pos = pChapter->add( gKDCMediaPlayer->currentPos(), pix );
	  if ( pos > -1 )
		  addItem( pos, gKDCMediaPlayer->currentPos(), pix );
	}
}

void KDCChapterEditor::deleteALL()
{
	if ( pChapter )
		pChapter->clear();
	pView->clear();
	while ( !pChapterJobs.isEmpty() )
		pChapterJobs.takeFirst().second->deleteLater();
	pChapterJobs.clear();
}

void KDCChapterEditor::removeChapters()
{
	if ( !pChapter )
		return;
	QList<QListWidgetItem*> items = pView->selectedItems();
	if ( !items.isEmpty() )
	{
		for ( int i=0; i<items.size(); ++i )
			pChapter->remove( items.at( i )->data( Qt::EditRole ).toInt() );
		display();
	}
}
